package com.micai.springboot.queue;

import com.micai.springboot.entity.sys.SLogEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 描述：系统操作日志队列(进程间队列)
 * <p>
 * Author: 赵新国
 * Date: 2017/12/13 14:49
 */
public class SLogQueue {

    private static final Logger logger = LoggerFactory.getLogger(SLogQueue.class);

    /**
     * 队列大小
     */
    public static final int QUEUE_MAX_SIZE = 1000;

    private static SLogQueue sLogQueue = new SLogQueue();

    /**
     * 阻塞队列
     */
    private BlockingQueue blockingQueue = new LinkedBlockingQueue(QUEUE_MAX_SIZE);

    private SLogQueue() {

    }

    public static SLogQueue getInstance() {
        return sLogQueue;
    }

    /**
     * 消息入队，如果入队元素为空，队列阻塞
     * @param sLogEntity
     */
    public void put(SLogEntity sLogEntity) {
        // 队列满了就阻塞，不抛出异常
        try {
            this.blockingQueue.put(sLogEntity);
        } catch (InterruptedException e) {
            e.printStackTrace();
            logger.error("队列满了: {}", e.getMessage());
        }
    }

    /**
     * 消息出队，如果队列为空，队列阻塞
     * @return
     */
    public SLogEntity take() {
        SLogEntity sLogEntity = null;
        // 队列为空，队列阻塞，只有中断等待时，才会抛出InterruptedException异常
        try {
            sLogEntity = (SLogEntity) this.blockingQueue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
            logger.error("队列中断等待: {}", e.getMessage());
        }
        return sLogEntity;
    }

    /**
     * 消息入队
     * @param sLogEntity
     * @return
     */
    public boolean push(SLogEntity sLogEntity) {
        // 队列满了就抛出异常，不阻塞
        return this.blockingQueue.add(sLogEntity);
    }

    /**
     * 消息出队
     * @return
     */
    public SLogEntity poll() {
        SLogEntity sLogEntity = null;
        try {
            sLogEntity = (SLogEntity) this.blockingQueue.poll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sLogEntity;
    }

    /**
     * 获取队列大小
     * @return
     */
    public int size() {
        return this.blockingQueue.size();
    }

}
